<?php
/**
 * @see Alinks_ImportExport_Export_Abstract
 */
require_once('Alinks/ImportExport/Export/Abstract.php');

/**
 * Utility class for exporting the defined keyphrases as CSV
 *
 * Copyright (C) 2008  Sean Hickey
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @author Sean Hickey <sean@headzoo.com>
 * @version $Id: Csv.php 390 2008-07-03 05:40:51Z sean $
 * @package Alinks_ImportExport
 */
class Alinks_ImportExport_Export_Csv extends Alinks_ImportExport_Export_Abstract
{
	/**
	 * Returns the keyphrases as an CSV string
	 *
	 * @return string
	 */
	public function export()
	{
		if (empty($this->_options[self::EXPORT_HASHES])) {
			$keyphrases = Alinks_Registry::get('Alinks_Keyphrase_Keeper')->fetchAll();
		} else {
			$keyphrases = Alinks_Registry::get('Alinks_Keyphrase_Keeper')->fetchByHashes($this->_options[self::EXPORT_HASHES]);
		}
		
		$csvs = array();
		$csvs[] = 'Phrase,Description,Created,Factory,Options,Hash';
		
		foreach($keyphrases as $keyphrase) {
			$csv = $this->_escape($keyphrase->getPhrase()) . ',';
			$csv .= $this->_escape($keyphrase->getDescription()) . ',';
			$csv .= $this->_escape(date('Y-m-d H:i:s', $keyphrase->getCreated())) . ',';
			$csv .= $this->_escape($keyphrase->getFactory()) . ',';
			$csv .= $this->_escape($this->_getOptionsString($keyphrase->getOptions())) . ',';
			$csv .= $this->_escape($keyphrase->getHash());
			$csvs[] = $csv;
		}
		
		return join("\r\n", $csvs);
	}
	
	/**
	 * Returns the MIME type for the exported document
	 *
	 * @return string
	 */
	public function getMimeType()
	{
		return 'text/csv';
	}
	
	/**
	 * Returns the file extension for the exported document
	 *
	 * @return string
	 */
	public function getFileExt()
	{
		return 'csv';
	}
	
	/**
	 * Returns the keyphrase options as a string
	 *
	 * @param array $options The keyphrase options
	 * @return string
	 */
	protected function _getOptionsString(array $options)
	{
		$o = array();
		foreach($options as $key => $value) {
			$o[] = '"' . $key . '" = "' . $value . '"';
		}
		
		return join(', ', $o);
	}
	
	/**
	 * Escapes a value for use in a CSV line
	 *
	 * @param string $value The value to escape
	 * @return string
	 */
	protected function _escape($value)
	{
		if (strstr($value, '"') !== false) {
			$value = str_replace('"', '""', $value);
		}
		$value = '"' . $value . '"';
		
		return $value;
	}
}